﻿using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using CRM.Extensions;
using CRM.Models.Email;
using Newtonsoft.Json;

namespace CRM.ViewModels.Email
{
    public class EmailMarketingVM
    {
        private readonly MyDbContext _dbContext;

        public EmailMarketingVM(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public int Id { get; set; }
        public int UserId { get; set; }
        public int OemId { get; set; }
        public int CompanyId { get; set; }
        public int GroupId { get; set; }
        public string Title { get; set; }
        public string[] Addresser { get; set; }
        public bool ShowAsEmail { get; set; }
        public string ReplyEmail { get; set; }
        // public record AddresseeObject(int? id, string name=default, string email="",bool isRead=false,bool isReply=false,[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]bool  isFailed=true);
        
        public record AddresseeObject(int? id, string name=default, string email="",bool isRead=false,bool isReply=false,bool  isFailed=true);
        public AddresseeObject[] Addressee { get; set; }
        public string EmailSubject { get; set; }
        public string EmailContent { get; set; }
        public int SubmitNum  { get; set; }
        public int SendingNum  { get; set; }
        public int OpenNum { get; set; }
        public int ReplyNum { get; set; }
        public EmailMarketing.TypeEnum Type { get; set; }
        public EmailMarketing.StateEnum State { get; set; }
        public DateTime? TimingTransmission { get; set; }

        public string TypeOfRequest { get; set; }

        public string Server { get; set; } = string.Empty;

        private EmailPlatform EmailPlatform => Server.Equals("rushemail", StringComparison.InvariantCultureIgnoreCase)
            ? EmailPlatform.Rushmail
            : EmailPlatform.Mailjet;
        
        //public List<string> Images
        //{
        //    get => ImagesStr.Split(',').ToList();
        //    set => ImagesStr = string.Join(',', value);
        //}

        public EmailMarketing NewModel(MyDbContext dbContext, Models.User user)
        {
            var AddresserInfoJson = "[]";
            var Type = EmailMarketing.TypeEnum.Server;
            switch (TypeOfRequest)
            {
                case "server":

                    break;
                case "free":
                    var res =
                        dbContext.EmailConfig
                            .Where(m => m.OemId == user  .OemId && m.CompanyId == user.CompanyId &&
                                        m.GroupId == user.GroupId && m.UserId == user.Id)
                            .Where(m => Addresser.Contains(m.Id.ToString())).ToList();
                    var info = res.Select((r) => new
                        {r.Id, r.EmailType, r.Driver, r.Host, r.Port, r.EmailAddress, r.Secret}).ToList();
                    AddresserInfoJson = JsonConvert.SerializeObject(info);
                    Type = EmailMarketing.TypeEnum.Free;
                    break;
            }

            var addresseeInfoFilter = Addressee.DistinctBy(r => r.email.ToLower());
            var addresseeInfo = addresseeInfoFilter.Select(r => new AddresseeObj() {Addressee = r.email, Name = r.name, Id = r.id, IsRead = false, IsReply = false, IsFailed = true});
            var submitNum = Addressee.Length;
            var settings = dbContext.Oem.Where(o => o.Id == user.OemId).Select(o => o.EmailSettings.EmailPlatform)
                .First();
            var emailPlatform = settings;
            var addresseeInfoJson = JsonConvert.SerializeObject(addresseeInfo);
            var result_model = new EmailMarketing()
            {
                UserId = user.Id,
                OemId = user.OemId,
                CompanyId = user.CompanyId,
                GroupId = user.GroupId,
                Title = Title,
                State = State,
                Type = Type,
                Addresser = AddresserInfoJson,
                ShowAsEmail = ShowAsEmail,
                ReplyEmail = ReplyEmail,
                SubmitNum = submitNum,
                Addressee = addresseeInfoJson,
                EmailContent = EmailContent,
                EmailSubject = EmailSubject,
                TimingTransmission = TimingTransmission ?? DateTime.Now,
                EmailPlatform = emailPlatform,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now,
            };
            return result_model;
        }

        public  string JsonSerializer(object o)
        {
            DataContractJsonSerializer se = new DataContractJsonSerializer(o.GetType(), new DataContractJsonSerializerSettings()
            {
                UseSimpleDictionaryFormat = true
            });
            //实例化一个内存流，用于存放序列化后的数据
            MemoryStream stream = new MemoryStream();
            //使用WriteObject序列化对象
            se.WriteObject(stream, o);
            //写入内存流中
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            //通过UTF8格式转换为字符串
            return Encoding.UTF8.GetString(dataBytes);
        }
        
        //public SocialMarketingTask EditModel(SocialMarketingTask task)
        //{
        //    task.Name = Name;
        //    task.Content = Content;
        //    task.ImagesStr = ImagesStr;
        //    task.UpdatedAt = DateTime.Now;
        //    return task;
        //}
    }


    public class EmailMarketingListQuery
    {
        public DateTime[] CreatedAt { get; set; }
        public int? State { get; set; }
        public  string Title { get; set; }
        public  int Limit { get; set; }
        public  int Page { get; set; }
        public int[] Ids { get; set; }
    }
}